package com.niji.littly_donkey_android.activity;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.android.volley.*;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.common.MultipartRequest;
import com.niji.littly_donkey_android.config.QiniuLabConfig;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.*;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.AsyncRun;
import com.qiniu.pili.droid.shortvideo.PLShortVideoUploader;
import com.qiniu.pili.droid.shortvideo.PLUploadProgressListener;
import com.qiniu.pili.droid.shortvideo.PLUploadResultListener;
import com.qiniu.pili.droid.shortvideo.PLUploadSetting;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;
import ru.alexbykov.nopermission.PermissionHelper;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ShootingReleaseActivity extends BaseActivity {
    private static final String TAG = "ShootingReleaseActivity";

    private Button shooting_release_return;

    private TextView shooting_screen;

    private Button shooting_screen_btn;

    private ImageView shooting_video_img;

    private VideoView shooting_video;

    private static String photoPath = null;

    private UploadManager uploadManager;

    private Bitmap localVideoBitmap;

    private String attractionsId;

    private Button shooting_release_video;

    private static Map<String, String> qingNiuToken;

    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private static final int CHOOSE_PHOTO = 2;

    private PermissionHelper permissionHelper;//权限申请
    String[] PermissionString={//需要提醒用户申请的权限
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shooting_release);
        ini();
        shootingReleaseReturn();
        shootingScreen();
        shootingScreenBtn();
        submitVideo();
        permission();
    }

    /**
     * 提交作品
     */
    private void submitVideo() {
        shooting_release_video = findViewById(R.id.shooting_release_video);
        shooting_release_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(photoPath == null){
                    Toast.makeText(ShootingReleaseActivity.this,"请从编辑页面处上传视频",Toast.LENGTH_LONG).show();
                }else {
                    qingNiuToken.put("filePath",photoPath);
                    uploadQiNiuVideo(qingNiuToken);
                    postVideo();
                }
            }
        });
    }

    private void permission() {
        permissionHelper = new PermissionHelper(this);//权限申请使用
        permissionHelper.check(PermissionString).onSuccess(new Runnable() {
            @Override
            public void run() {Log.e("e", "run: 允许" ); }
        }).onDenied(new Runnable() {
            @Override
            public void run() { Log.e("e", "run: 权限被拒绝" ); }
        }).onNeverAskAgain(new Runnable() {
            @Override
            public void run() { Log.e("e", "run: 权限被拒绝，下次不会在询问了" ); }
        }).run();
    }


    private void ini() {
        TextView commission_enjoy = findViewById(R.id.commission_enjoy);
        shooting_video = findViewById(R.id.shooting_video);
        getQingNiuToken();
        Intent intent = getIntent();
        attractionsId = intent.getStringExtra("attractions_id");
        if(attractionsId != null){
            if(!attractionsId.equals("")){
                commission_enjoy.setText("已加入佣金模式");
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.shooting_release;

    }
    @Override
    protected int getStatusBarColor() {
        return R.color.white_easy_photos;
    }

    private void shootingScreenBtn() {
        shooting_screen_btn = findViewById(R.id.shooting_screen_btn);
        shooting_screen_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShootingReleaseActivity.this, RelatedGoodsActivity.class);
                intent.putExtra("className","ShootingReleaseActivity");
                startActivity(intent);
                finish();
            }
        });
    }

    private void shootingScreen() {
        shooting_screen = findViewById(R.id.shooting_screen);
        shooting_screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShootingReleaseActivity.this, RelatedGoodsActivity.class);
                intent.putExtra("className","ShootingReleaseActivity");
                startActivity(intent);
                finish();
            }
        });
    }

    /**
     * 获取七牛token
     */
    private void getQingNiuToken(){
        qingNiuToken = new HashMap<>();
        String url = UrlUtil.URL + "/video/token";
        RequestQueue requestQueue = Volley.newRequestQueue(ShootingReleaseActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET,url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map1 = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map1.get("code");
                    if(code == 0){
                        Map<String,String> data = (Map) map1.get("data");
                        String token = data.get("token");
                        String key = data.get("key");
                        String domain = data.get("domain");
                        qingNiuToken.put("token",token);
                        qingNiuToken.put("key",key);
                        qingNiuToken.put("domain",domain);
                    }else if (code == -1) {
                        Toast.makeText(ShootingReleaseActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(ShootingReleaseActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode", "-1");
                        startActivity(intent);
                        finish();
                    } else {
                        String message = (String) map1.get("message");
                        Toast.makeText(ShootingReleaseActivity.this,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(ShootingReleaseActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(stringRequest);

    }

    /**
     * 视频上传
     * @param map
     */
    private void uploadQiNiuVideo(Map<String,String> map){
        if (this.uploadManager == null) {
            this.uploadManager = new UploadManager();
        }
        upload(map);

    }
    private void upload(Map<String,String> map){
        UploadOptions uploadOptions = new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    @Override
                    public void progress(String key, double percent) {
//                        System.out.println(percent);
                    }
                }, null);
        String uploadFile = map.get("filePath");
        String uploadFileKey = map.get("key");
        String uploadToken = map.get("token");
        File file = new File(uploadFile);
        this.uploadManager.put(file, uploadFileKey, uploadToken,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo respInfo,
                                         JSONObject jsonData) {
                        AsyncRun.runInMain(new Runnable() {
                            @Override
                            public void run() {
                                // reset status

                            }
                        });
                        if (respInfo.isOK()) {
                            try {
                                String fileKey = jsonData.getString("key");
                                String fileHash = jsonData.getString("hash");
                                Log.i("TAG + fileKey",fileKey);
                                Log.i("TAG + fileHash",fileHash);
                                final String videoUrl = map.get("domain") + "/" + fileKey;
                                Log.i("TAG + videoUrl",videoUrl);
                                if(Uri.parse(videoUrl)!=null){
                                    shooting_video.setVideoURI(Uri.parse(videoUrl));
                                    shooting_video.start();
                                    shooting_video_img.setVisibility(View.INVISIBLE);
                                }
                            } catch (JSONException e) {
                                AsyncRun.runInMain(new Runnable() {
                                    @Override
                                    public void run() {


                                    }
                                });

                                if (jsonData != null) {
                                    Log.i("TAG",jsonData.toString());
                                }
                            }
                        } else {
                            AsyncRun.runInMain(new Runnable() {
                                @Override
                                public void run() {
                                    Log.i("TAG","上传文件失败");
                                }
                            });
                            Log.i("TAG",respInfo.toString());
                            if (jsonData != null) {
                                Log.i("TAG",jsonData.toString());
                            }
                        }
                    }

                },uploadOptions);
    }

    /**
     * 返回，保存发布视频信息
     */
    private void shootingReleaseReturn() {
        shooting_release_return = findViewById(R.id.shooting_release_return);
        shooting_release_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Utils.isFastDoubleClick()){
                    Toast.makeText(ShootingReleaseActivity.this,"您提交的太频繁了，请稍后再试",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                    finish();
                }

            }
        });

    }

    /**
     * 发布视频信息
     */
    private void postVideo() {
        EditText shooting_message = findViewById(R.id.shooting_message);
        if(qingNiuToken != null){
            File file = null;
            String title = shooting_message.getText().toString().trim();
            if (ContextCompat.checkSelfPermission(ShootingReleaseActivity.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ShootingReleaseActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE);
            } else {

                file = BitMapUtil.getFile(localVideoBitmap,ShootingReleaseActivity.this);
            }
            Log.i(TAG,file.getClass().toString());
            String videoUrl = qingNiuToken.get("domain") + "/" +  qingNiuToken.get("key");
            String url = UrlUtil.URL + "/video/add";
            if("".equals(title)){
                Toast.makeText(ShootingReleaseActivity.this,"视频标题不能为空",Toast.LENGTH_SHORT).show();
            }else if(file == null){
                Toast.makeText(ShootingReleaseActivity.this,"视频封面不能为空",Toast.LENGTH_SHORT).show();
            }else if(videoUrl.equals("")){
                Toast.makeText(ShootingReleaseActivity.this,"视频地址不能为空",Toast.LENGTH_SHORT).show();
            } else {
                Map<String, String> map = new HashMap<String, String>();
                if (attractionsId != null){
                    if(!attractionsId.equals("")){
                        map.put("attractions_id", attractionsId);
                    }
                }
                map.put("title", title);
                map.put("url", videoUrl);
                shooting_message.setText("");
                OkHttpClient client = new OkHttpClient();
                // form 表单形式上传
                MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
                if(file != null){
                    // MediaType.parse() 里面是上传的文件类型。
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    localVideoBitmap.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);
                    InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                    RequestBody body = RequestBody.create(MediaType.parse("image/*"),file);
                    String filename = file.getName();
                    // 参数分别为， 请求key ，文件名称 ， RequestBody
                    requestBody.addFormDataPart("cover", file.getName(), body);
                }
                if (map != null) {
                    // map 里面是请求中所需要的 key 和 value
                    for (Map.Entry entry : map.entrySet()) {
                        requestBody.addFormDataPart(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
                    }
                }
                String sesseionid = new ConnectViaSession(ShootingReleaseActivity.this).GetSession();
                okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(requestBody.build()).addHeader("cookie",sesseionid).tag(ShootingReleaseActivity.this).build();
                // readTimeout("请求超时时间" , 时间单位);
                client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("lfq" ,"onFailure");
                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {
                        if (response.isSuccessful()) {
                            String str = response.body().string();
                            Log.i("lfq", response.message() + " , body " + str);
                            try {
                                Map<String, Object> map1 = JsonUtil.jsonToMap(str);
                                Integer code = (Integer) map1.get("code");
                            if (code == 0) {
                                String data = (String) map1.get("data");
                                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                finish();
                            } else if (code == -1) {
                                Toast.makeText(ShootingReleaseActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(ShootingReleaseActivity.this, GetPhoneCodeActivity.class);
                                intent.putExtra("loginCode", "-1");
                                startActivity(intent);
                                finish();
                            } else {
                                String data = (String) map1.get("message");
                                Log.i(TAG,data);
                                Toast.makeText(ShootingReleaseActivity.this, data, Toast.LENGTH_SHORT).show();
                            }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            Log.i("lfq" ,response.message() + " error : body " + response.body().string());
                        }
                    }
                });
            }
        }
    }

    /**
     * 请求读写SDK权限
     */
    public void chooseVideo(View view) {
        if (ContextCompat.checkSelfPermission(ShootingReleaseActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ShootingReleaseActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE);
        } else {
            openAlbum();
        }
    }


    /**
     * 打开图片浏览器
     */
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "拒绝读取SD卡权限将无法获取照片", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        handleImageAfterKitKat(data);
                    } else {
                        handleImage(data);
                    }
                }
                break;
        }
    }

    /**
     * API19之后处理内容
     *
     * @param data onActivityResult 返回结果
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageAfterKitKat(Intent data) {
        /*ParcelFileDescriptor parcelFileDescriptor =
                null;
        try {
            parcelFileDescriptor = getContentResolver().openFileDescriptor(data.getData(), "r");
            Log.i(TAG, "handleImageAfterKitKat: " + parcelFileDescriptor.toString());
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            result.setImageBitmap(image);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        String imagePath = null;
        Uri uri = data.getData();
        Log.i(TAG, uri.toString());
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，通过documentId处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];    // 解析出数字格式id
                String selection = MediaStore.Video.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, selection);
                photoPath = imagePath;
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
                photoPath = imagePath;
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
            photoPath = imagePath;
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
            photoPath = imagePath;
        }
        displayImage(imagePath);
    }

    /**
     * 处理返回结果
     *
     * @param data onActivityResult 返回结果
     */
    private void handleImage(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    /**
     * 根据图片路径，显示图片
     */
    private void displayImage(String imagePath) {
        shooting_video = findViewById(R.id.shooting_video);
        shooting_video_img = findViewById(R.id.shooting_video_img);
        if (imagePath != null) {
//            shooting_video.setVideoPath(imagePath);
            localVideoBitmap = VideoUtil.getInstance().getLocalVideoBitmap(imagePath);
            shooting_video_img.setVisibility(View.VISIBLE);
            shooting_video_img.setImageBitmap(localVideoBitmap);
        } else {
            Toast.makeText(this, "照片路径为空", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 使用ContentProvider获取视频路径
     *
     * @param uri       图片uri
     * @param selection 条件
     * @return 图片路径
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

}
